//
//  CTVUser.m
//  Channltv
//
//  Created by Bruno  Keymolen on 19/07/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVUser.h"
#import "CTVConfig.h"
#import "CTVHTTP.h"

@implementation CTVUser



-(void) dealloc{ 
	[m_fullName release];	
	[m_uid release];	
	[m_alias release];
	[m_email release];	
		
	[super dealloc]; //do not forget to transmit to the superclass 
} 



-(NSString*)fullName{
	return m_fullName;
}

-(NSString*)uid{
	return m_uid;
}

-(NSString*)alias{
	return m_alias;
}

-(NSString*)email{
	return m_email;
}

-(BOOL)confirmed{
	return m_confirmed;
}

-(int)loginToChannelTVByAlias:(NSString*)alias andPassword:(NSString*)password{
	//Logout the previous user if needed
	if(m_isLogon == TRUE){
		[self logout];
	}
	
	NSString* url = [NSString stringWithFormat:@"http://%@/login.xml?login=%@&password=%@", [[CTVConfig GetInstance] CTVServer], alias, password];
	
	[self setAlias:alias];
	[self setPassword:password];
	
	CTVHTTP* chttp = [[[CTVHTTP alloc] init] autorelease];
	NSString* retString = [chttp httpGet:url];
	
	if(![retString hasPrefix:@"<result>Login successful !</result>"]){
		NSLog(@"Login to channl.tv failed");
		m_isLogon = FALSE;
		return -10; //Login failed
	}
	
	m_isLogon = TRUE;
	
	NSLog(@"Login to channl.tv ok");
	
	[self loadCurrentUserInfo];	
				
	return 0;

	
}


-(int)loadCurrentUserInfo{
	if(m_alias == nil){
		return -1;
	}
	
	NSString* url =  [NSString stringWithFormat:@"http://%@/viewers/current.xml", [[CTVConfig GetInstance] CTVServer]];
	
	NSURLRequest* urlRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
							  cachePolicy:NSURLRequestUseProtocolCachePolicy
							  timeoutInterval:60.0];

	NSURLDownload* urlDown=[[NSURLDownload alloc] initWithRequest:urlRequest delegate:self];
		
		
	if(urlDown != nil){
		NSString* xmlpath = [NSString stringWithFormat:@"%suser.xml",[[[CTVConfig GetInstance] tmpdir] UTF8String]];
		// set the destination file now
		[urlDown setDestination:xmlpath allowOverwrite:YES];
		
		return 0;
	}
	
	return -1;
}



//Download finish
- (void)downloadDidFinish:(NSURLDownload *)download{
	int ret;

    // release the connection
    [download release];

	ret = [self parseFromCache];
}


//Download error
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error{
	
    // release the connection
    [download release];
	
	m_confirmed = FALSE;			
}


- (int)parseFromCache{

	NSString* xmlpath = [NSString stringWithFormat:@"%suser.xml",[[[CTVConfig GetInstance] tmpdir] UTF8String]];

	NSURL *furl = [NSURL fileURLWithPath:xmlpath];   
	NSError *err=nil;	
	NSXMLDocument* xmlDoc = [[[NSXMLDocument alloc] initWithContentsOfURL:furl options:(NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA) error:&err] autorelease]; 
	
	if(xmlDoc == nil){
		return -1;
	}

	//Parse the XML
	NSArray* user = [xmlDoc nodesForXPath:@"//viewer" error:&err];
		
	//Validity check, there must be one user only
	if([user count] != 1){
		m_confirmed = FALSE;
		return -2;
	}	
	
	//Loop through the child nodes
	int childt, childcnt;
	NSXMLNode *userNode, *childNode;
	userNode = [user objectAtIndex:0];
	childcnt = [userNode childCount];
	NSString *sVal, *oVal;
	
	for (childt=0;childt<childcnt;childt++) {
		childNode = [userNode childAtIndex:childt];
		if([childNode kind] == NSXMLElementKind) {
			sVal = [childNode stringValue];
			oVal = [childNode name];
			if (sVal != nil) {
				if( [oVal caseInsensitiveCompare:@"email"] == NSOrderedSame){
					[self setEmail:sVal]; 
				}else if ([oVal caseInsensitiveCompare:@"fullname"] == NSOrderedSame){
					[self setFullName:sVal]; 
				}else if ([oVal caseInsensitiveCompare:@"id"] == NSOrderedSame){
					[self setID:sVal]; 				
				}else if ([oVal caseInsensitiveCompare:@"activated-at"] == NSOrderedSame){
					m_confirmed = TRUE;
				}
			}
		}
	}
	
	return 0;
}

-(void)setEmail:(NSString*)email{
	[email retain];
	[m_email release];
	m_email = email;
}

-(void)setFullName:(NSString*)fullName{
	[fullName retain];
	[m_fullName release];
	m_fullName = fullName;
}

-(void)setID:(NSString*)uid{
	[uid retain];
	[m_uid release];
	m_uid = uid;
}

-(void)setAlias:(NSString*)alias{
	[alias retain];
	[m_alias release];
	m_alias = alias;
}

-(void)setSynchronized:(BOOL)synchronized{
	m_synchronized = synchronized;
}

-(void)setPassword:(NSString*)password{
	[password retain];
	[m_password release];
	m_password = password;
}

-(NSString*)password{
	return m_password;
}

-(BOOL)synchronized{
	return m_synchronized;
}

-(void)setIsLogon:(BOOL)isLogon{
	m_isLogon = isLogon;
}

-(BOOL)isLogon{
	return m_isLogon;
}


-(int)logout{
	int ret = 0;
	NSString* url = [NSString stringWithFormat:@"http://%@/logout", [[CTVConfig GetInstance] CTVServer]];
		
	CTVHTTP* chttp = [[[CTVHTTP alloc] init] autorelease];
	NSString* retString = [chttp httpGet:url];
	
	NSRange frange = [retString rangeOfString:@"You have been logged out"];
	
	if( frange.location == NSNotFound ){
			ret = -1;
	}else{
			ret = 0;
	}
	m_isLogon = FALSE;
	
	return ret;
}

@end
